


import 'package:flutter/material.dart';
class SearchAppBar extends StatefulWidget {
  SearchAppBar({Key? key, required this.hintLabel, required this.onChanged})
      : super(key: key);
  final String hintLabel;
  // 回调函数
  final Function(String) onChanged;

  @override
  State<StatefulWidget> createState() => _SearchAppBarState();
}

class _SearchAppBarState extends State<SearchAppBar> {
  // 焦点对象
  FocusNode _focusNode = FocusNode();
  // 文本的值
  String searchVal = '';
  //用于清空输入框
  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    //  获取焦点
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _focusNode.requestFocus();
    });
  }

  @override
  void dispose() {
    widget.onChanged('');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    // 获取屏幕尺寸
    MediaQueryData queryData = MediaQuery.of(context);
    return Container(
      // 宽度为屏幕的0.75
      // width: queryData.size.width * 0.75,
      // appBar默认高度是56，这里搜索框设置为40
      height: 30,
      // 设置padding
      padding: EdgeInsets.only(left: 15),
      // 设置修饰
      decoration: BoxDecoration(
          color: Colors.grey.withOpacity(0.3),
          borderRadius: BorderRadius.circular(20)
      ),
      child: TextField(
        controller: _controller,
        // 自动获取焦点
        focusNode: _focusNode,
        autofocus: true,
        decoration: InputDecoration(
            // hintText: widget.hintLabel,
            contentPadding: EdgeInsets.fromLTRB(0, 0, 0, 16),
            hintStyle: TextStyle(color: Colors.grey,fontSize: 12),
            // 取消掉文本框下面的边框
            border: InputBorder.none,
            // icon: Padding(
            //     padding: const EdgeInsets.only(left: 0, top: 0),
            //     child: Icon(
            //       Icons.search,
            //       size: 18,
            //       color: Theme.of(context).primaryColor,
            //     )),
            //  关闭按钮，有值时才显示
            //   清空内容
            // setState(() {
            //   _controller.clear();
            // });
            // widget.onChanged('');
            // suffixIcon: searchVal.isNotEmpty
            //     ? Icon(Icons.close)
            //     : null),
        ),
        // cursorHeight: 12.r,
        style: TextStyle(fontSize: 14),
        onChanged: (value) {
          setState(() {
            searchVal = value;
          });
          widget.onChanged(value);
        },
        onSubmitted: (value) {

        },
      ),
    );
  }
}